require('./index.css')
require('page/common/top-head-menu/index.js')
require('page/common/head-search/index.js')
require('page/common/footer/index.js')
require('page/common/bread-menu/index.js')
require('page/common/right-easy-menu/index.js');
require('util/pic_tab');
require('util/webuploader/webuploader.css');
import _mm from 'util/mm.js'
import _tool from 'util/tool.js'
import _all from 'service/all-service';

const page = {
    cartData: {
        file: '',
        email: '',
        message: '',
        orderDetailList: []
    },
    init() {
        this.loadCartList();
        this.bindEvent();
        this.initUploader();
    },
    list: [],
    loadCartList() {
        const list = !!localStorage.getItem('cartList')?JSON.parse(localStorage.getItem('cartList')):[]
        const tpl = require('./cartList.string'), _this = this;
        const html = _mm.renderHtml(tpl, {data: list});
        _this.list = list;
        $('.cartList').html(html);
    },
    bindEvent() {
        const _this = this;
        const changeNum = function () {
            const $this = $(this), num = $this.val(), id = $this.attr('data-id');
            for (let i = 0; i < _this.list.length; i++) {
                if (_this.list[i].id === id) {
                    _this.list[i].num = num;
                }
            }
            _this.saveData(JSON.stringify(_this.list));
        };
        const removeOne = function () {
            const $this = $(this), id = $this.attr('data-id');
            for (let i = 0; i < _this.list.length; i++) {
                if (_this.list[i].id === id) {
                    const lay = layer.open({
                        type: 1,
                        title: false,
                        content: '<div style="width: 100%;text-align: center;padding: 10px 0px;">Are you sure you want to delete it?</div>',
                        btn:['sure', 'cancel'],
                        btnAlign: 'c',
                        area:['420px', 'auto'],
                        btn1: function () {
                            _this.list.splice(i, 1);
                            layer.close(lay);
                            _this.saveData(JSON.stringify(_this.list));
                            _this.loadCartList();
                        },
                        btn2: function () {
                            layer.close(lay);
                        }
                    });
                }
            }
        };
        const removeAll = function () {
            const lay = layer.open({
                type: 1,
                title: false,
                content: '<div style="width: 100%;text-align: center;padding: 10px 0px;">Are you sure you want to delete them?</div>',
                btn:['sure', 'cancel'],
                btnAlign: 'c',
                area:['420px', 'auto'],
                btn1: function () {
                    localStorage.removeItem('cartList');
                    layer.close(lay);
                    _this.loadCartList();
                },
                btn2: function () {
                    layer.close(lay);
                }
            });

        };
        const sendMessage = function () {
            for (let i = 0; i < _this.list.length; i++) {
                const pId = _this.list[i].id, pQuantity = _this.list[i].num, pUnit = _this.list[i].unit;
                _this.cartData.orderDetailList.push({pId, pQuantity, pUnit});
            }
            _all.sendCartList(JSON.stringify(_this.cartData), res => {
                _tool.msgShakeLayer('Successful submission！');
                localStorage.removeItem('cartList');
            }, err => {
                _tool.msgShakeLayer(err.message);
            })
        };
        const blurEmail = function () {
            _this.cartData.email = $.trim($(this).val());
        };
        const blurMessage = function () {
            _this.cartData.message = $.trim($(this).val());
        };
        $(document).on('click', '.model-num', changeNum);
        $(document).on('click', '.remove-pro', removeOne);
        $(document).on('click', '.btn-bounce', removeAll);
        $(document).on('click', '.send-message', sendMessage);
        $(document).on('blur', '#email', blurEmail);
        $(document).on('blur', '#message', blurMessage);
    },
    saveData(data) {
        localStorage.setItem('cartList', data);
    },
    initUploader() {
        const _this = this;
        // 文件上传
        jQuery(function () {
            var $ = jQuery,$list = $('#thelist'),$btn = $('#picker'),state = 'pending',uploader;
            uploader = WebUploader.create({
                // swf文件路径
                swf: './Uploader.swf',
                // 文件接收服务端。
                server: _mm.getServerUrl('/web/order/accessory'),
                fileVal: "upload",
                pick: '#picker'
            });

            // 当有文件添加进来的时候
            uploader.on('fileQueued', function (file) {
                uploader.upload();
            });

            uploader.on('uploadBeforeSend', function (obj, data, headers) {
            })

            // 文件上传过程中创建进度条实时显示。
            uploader.on('uploadProgress', function (file, percentage) {

            });

            uploader.on('uploadSuccess', function (file, res) {
                console.log(res);
                if (res.errorCode !== 0) {
                    $list.html('<div style="color: red">error:'+ res.message + '</div>');
                } else {
                    $list.html('<div style="color: red">Upload Success!</div>');
                    _this.cartData.file = res.data;
                }
            });

            uploader.on('uploadError', function (file, err) {
                $('#' + file.id).find('p.state').text(err.message);
                _this.init();
            });

            uploader.on('uploadComplete', function (file) {
                $('#' + file.id).find('.progress').fadeOut();
            });

            uploader.on('all', function (type) {
                if (type === 'startUpload') {
                    state = 'uploading';
                } else if (type === 'stopUpload') {
                    state = 'paused';
                } else if (type === 'uploadFinished') {
                    state = 'done';
                }
            });
        });
    }
};

module.export = page.init();